// import { SUCCESS_CODE } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageHeaderWrapper, ProTable } from '@ant-design/pro-components';
import { Button, message, Modal } from 'antd';
// import modal from 'antd/lib/modal';
import { useRef, useState } from 'react';
import ActivityDetail from './component/ActivityDetail';
import AddActivity from './component/addActivity';
import UpdataActivity from './component/updateActivity';
import { addAcitvity, deleteAcitvity, getAcitvitytable, getActivityDetail } from './service';
import type { activityItem, createactivityItem, DetailItem } from './types';

export default () => {
  const [parkDetailVisible, setParkDetailVisible] = useState<boolean>(false);
  const [addListVisible, setAddListVisible] = useState<boolean>(false);
  const [updateListVisible, setUpdateListVisible] = useState<boolean>(false);
  const [currentId, setCurrentId] = useState<string>('');
  const [currItem, setCurrItem] = useState<DetailItem | null>(null);
  const [pageTotal, setPageTotal] = useState<number | undefined>(0);
  const actionRef = useRef<ActionType>();

  const createActivity = async (fields: createactivityItem) => {
    const hide = message.loading('正在提交');
    try {
      await addAcitvity(fields);
      hide();
      setAddListVisible(false);
      actionRef.current?.reload();
      message.success('添加成功！');
    } catch (error) {
      hide();
      message.error('添加失败！未知的错误！');
      setAddListVisible(false);
    }
  };

  const handleRemove = async (fields: { id: string }) => {
    const hide = message.loading('正在删除');
    try {
      await deleteAcitvity(fields);
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除成功');
      actionRef.current?.reload();
      return false;
    }
  };

  const columns: ProColumns<activityItem>[] = [
    {
      title: '活动名称',
      dataIndex: 'name',
      ellipsis: true,
      onFilter: true,
      width: '15vw',
    },
    {
      title: '活动地址',
      dataIndex: 'links',
      ellipsis: true,
      search: false,
      width: '45vw',
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                window.open(record.links);
              }}
            >
              {record.links}{' '}
            </a>
          </>
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (
        text,
        record,
        //  _, action
      ) => {
        const onClickRemove = () => {
          const { name, id } = record;
          Modal.confirm({
            title: `确定要删除 ${name} 吗？`,
            content: (
              <>
                <p>删除之后无法撤回，请谨慎操作！</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({ id });
            },
            centered: true,
            width: 600,
            style: { height: 400 },
          });
        };
        return (
          <>
            <a
              onClick={async () => {
                setUpdateListVisible(true);
                const curr = await getActivityDetail(record.id);
                setCurrItem(curr.data);
              }}
            >
              修改
            </a>
            <a style={{ width: 7 }}> </a>
            <a
              onClick={() => {
                message.info('正在加载数据');
                setCurrentId(record.id);
                setTimeout(() => {
                  setParkDetailVisible(true);
                }, 350);
              }}
            >
              查看
            </a>
            <a style={{ width: 7 }}> </a>
            <a onClick={onClickRemove}>删除</a>
          </>
        );
      },
    },
  ];
  return (
    <PageHeaderWrapper title="活动中心" content="提示：最多可以添加三条活动">
      <ProTable<activityItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        editable={{
          type: 'multiple',
        }}
        params={{}}
        request={async (params) => {
          const res = getAcitvitytable(params);
          setPageTotal((await res).total);
          return res;
        }}
        // rowKey="id"
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        pagination={{
          pageSize: 10,
          size: 'default',
        }}
        dateFormatter="string"
        headerTitle="活动中心"
        toolBarRender={() => [
          (!pageTotal || pageTotal < 3) && (
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setAddListVisible(true);
              }}
            >
              添加
            </Button>
          ),
        ]}
      />
      {addListVisible && (
        <AddActivity
          visible={addListVisible}
          unVisible={() => {
            setAddListVisible(false);
          }}
          onSubmit={createActivity}
        />
      )}
      {currItem && updateListVisible && (
        <UpdataActivity
          visible={updateListVisible}
          ruleData={currItem}
          unVisible={() => {
            setUpdateListVisible(false);
            setCurrItem(null);
          }}
          reloadFunc={() => actionRef.current?.reload()}
        />
      )}
      {
        <ActivityDetail
          visible={parkDetailVisible}
          onClose={() => {
            setParkDetailVisible(false);
          }}
          id={currentId}
        />
      }
    </PageHeaderWrapper>
  );
};
